package huas.ant.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import huas.ant.common.PageResult;
import huas.ant.constant.MemberConstant;
import huas.ant.dto.MemberDTO;
import huas.ant.entity.Member;
import huas.ant.mapper.MemberMapper;
import huas.ant.service.MemberService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.time.LocalDate;
import java.util.Random;

@Service
public class MemberServiceImpl implements MemberService {
    @Autowired
    private MemberMapper memberMapper;

    /**
     * 条件分页列表查询
     */
    @Override
    public PageResult page(Integer page, Integer pageSize, String name, Short gender) {
        //PageHelper设置分页参数
        PageHelper.startPage(page,pageSize);
        /**
         * 底层实现原理：ThreadLocal
         * startPage:将page,pageSize都存入本地空间，调用mapper的方法又取出进行动态拼接
         */
        //List<Member> MemberList = MemberMapper.page(name,gender);
        //获取的其实是一个ArrayList集合
        Page<Member> p = memberMapper.page(name,gender);

        return new PageResult(p.getTotal(),p.getResult());

    }

    /**
     * 添加会员
     */
    @Override
    @Transactional
    public void insert(MemberDTO memberDTO) {
        //调用持久层推荐使用实体类而非DTO
        Member member = new Member();
        BeanUtils.copyProperties(memberDTO,member);

        //补充基础数据

        //会员账号&卡号随机生成
        Random random = new Random();
        String accountTemp = "2023";
        for (int i = 0; i < 5; i++) {
            accountTemp += random.nextInt(10);
        }
        String account = accountTemp;
        String password = DigestUtils.md5DigestAsHex(MemberConstant.DEFAULT_PASSWORD.getBytes());
        LocalDate now = LocalDate.now();
        member.setMemberAccount(account);
        member.setPassword(password);
        member.setCreateTime(now);

        //添加会员表
        memberMapper.reset();
        memberMapper.insert(member);

    }

    @Override
    public Member findById(Integer id) {
        Member member = memberMapper.findById(id);
        return member;
    }

    /**
     * 修改会员
     */
    @Override
    public void update(Member member) {
        memberMapper.update(member);

    }
    /**
     * 删除会员
     */
    @Override
    public void delete(Integer id) {
        memberMapper.delete(id);
    }
}
